﻿using RpcClient.Collect;
using RpcClient.Config;
using RpcClient.Interface;
using RpcHelper;
using RpcHelper.Config;
using RpcHelper.IdGenerator;
using RpcModel;

namespace RpcClient.Identity
{
    [Attr.ClassLifetimeAttr(Attr.ClassLifetimeType.单例)]
    internal class IdentityService : IIdentityService
    {
        private static ushort _WorkId;
        private static void _InitWork()
        {
            if (_WorkId == 0)
            {
                IRemoteConfig config = new("GetIdgeneratorWorkId", "sys.sync", true, true);
                if (!RemoteCollect.Send<ushort>(config, out _WorkId, out string error))
                {
                    throw new ErrorException(error);
                }
            }
        }
        public static void InitServie()
        {
            _InitWork();
            LocalConfig.Local.RefreshEvent += Local_RefreshEvent;
            _Init();
        }

        private static void Local_RefreshEvent(IConfigCollect config, string name)
        {
            if (name == "rpc:Idgenerator" || name.StartsWith("rpc:Idgenerator:"))
            {
                _Init();
            }
        }

        private static void _Init()
        {
            IdgeneratorConfig config = LocalConfig.Local.GetValue<IdgeneratorConfig>("rpc:Idgenerator", new IdgeneratorConfig());

            IdentityConfig con = new()
            {
                WorkId = _WorkId,
                SeqBitLength = config.SeqBitLength,
                WorkerIdBitLength=config.WorkerIdBitLength,
                Method=config.Method,
                MaxSeqNumber = config.MaxSeqNumber,
                BaseTime=config.BaseTime,
                MinSeqNumber = config.MinSeqNumber,
                TimestampType = config.TimestampType
            };
            if (config.EnableDataCenter)
            {
                con.DataCenterId = (uint)RpcStateCollect.LocalSource.RegionId;
                con.DataCenterIdBitLength = config.DataCenterIdBitLength;
            }
            IdentityHelper.Init(con);
        }
        public long CreateId()
        {
            return IdentityHelper.CreateId();
        }

    }
}
